<?php
defined('BASEPATH') or exit('No direct script access allowed');


class MY_Controller extends CI_Controller
{

    public $userinfo = '';
    public $user_id = "";
    public $username = "";
    public $status = "";
    public $address = '';//页面位置
    public $group = 0; //用户组
    public $project = 1;  //所属项目  1京东  2拼多多
    public $host = "";
    public $is_vip = "";
    public $web_id = 1;


    public function __construct()
    {

        parent::__construct();
        $this->checklogin();
        $this->getwebid();

        $class = strtolower($this->router->class);
        if ($class != 'welcome' && $class != 'tools') {
            $this->initialinfo();
        }
    }


    public function initialinfo()
    {
        $userinfo = $this->session->userinfo;
        if (!isset($userinfo['group']) || $userinfo['group'] == 2 || $userinfo['group'] == 1) {
            $userinfo = $this->userinfo = $this->getcuserinfo(1);
            $this->setuserinfo($this->userinfo);
        } else {
            $this->userinfo = $userinfo;
        }

        $this->group = $userinfo['group'];
        $this->is_vip = $userinfo['VIP'];
        $this->user_id = $this->session->user_id;
    }

    public function addlog($info = array())
    {
        $TxtFileName = "Demo.txt";
        if (($TxtRes = fopen($TxtFileName, "w+")) === FALSE) {
            echo("创建可写文件：" . $TxtFileName . "失败");
            exit();
        }
        if (!$info) {
            $StrConents = json_encode($this->userinfo);
        } else {
            $StrConents = json_encode($info);
        }

        if (!fwrite($TxtRes, $StrConents)) { //将信息写入文件
            echo("尝试向文件" . $TxtFileName . "写入" . $StrConents . "失败！");
            fclose($TxtRes);
            exit();
        }
        fclose($TxtRes); //关闭指针
    }

    /**
     *
     * @param bool $getlist 是否获得list形式的数据
     */
    public function getwebid($getlist = false)
    {
        $host = HOST;
        if (!$host) {
            $host = 'www.xiaochao1.top';
        }
        $this->load->model('Jd_group_model');
        $host = str_replace("admin.", 'www.', $host);
        if ($host == "www.hunter.com") {
            $host = "local.hunter.com";
        }
        $MYredis = $this->MyRedis();
        $key = "hunterweblist";
        $res = $MYredis->hGet($key, $host);
        if (!$res) {
            $sql = "select * from jd_weblist where host= '$host'";
            $res = $this->Jd_group_model->GetBySql($sql, 0);
            $res = serialize($res);
            $MYredis->hSet($key, $host, $res);
            $ttl = $MYredis->ttl($key);
            if ($ttl == -1) {
                $MYredis->expire($key, 2 * 60);
            }
        }
        if ($res) {
            $res = unserialize($res);
        }
        if (empty($res)) {
            $res['code'] = 500;
            $res['msg'] = "weberror";
            $this->sendjsonmsg($res);
        }
        /* $res['qq']='http://www.xiaochao1.top/public/uploads/pic/webinfo/code3.jpg';
         $res['weixin']='http://www.xiaochao1.top/public/uploads/pic/webinfo/微信图片_20210106180710.jpg';*/
        $res['payee'] = '陈加明';
        $res['account'] = '6217751010017537493';
        $res['bankname'] = '徽商银行';

        $this->web_id = $res['id'];
        $this->session->web_id = $res['id'];
        $this->session->webinfo = $res;
        if ($getlist) {
            $msg['code'] = 0;
            $msg['list'] = $res;
            $this->sendjsonmsg($msg);
        }
    }

    /**
     * @param bool $getcath 是否优先获取缓存
     * @param string $getmsg 是否直接json 返回数据
     * @return mixed|string
     */
    public function getWebInfo($getcath = true, $getmsg = false)
    {
        $host = HOST;
        $row = $this->input->post();
        if (isset($row['host'])) {
            $host = 'www.xiaochao1.top';
            if (ISHOST) {
                $host = 'local.hunter.com';
            }
        }
        $host = str_replace("admin.", 'www.', $host);
        $this->load->model('Jd_group_model');
        $MYredis = $this->MyRedis();
        $key = "thiswebinfo";
        $res = $MYredis->hGet($key, $host);



        if (!$res || !$getcath) {
            $sql = "select * from jd_weblist where host= '$host'";
            $res = $this->Jd_group_model->GetBySql($sql, 0);
            $res = serialize($res);
            $MYredis->hSet($key, $host, $res);
            $ttl = $MYredis->ttl($key);
            if ($ttl == -1) {
                $MYredis->expire($key, 2 * 60);
            }
        }
        if ($res) {
            $res = unserialize($res);
        }


        /*   $userinfo = @$this->getcuserinfo(1);
           if ($userinfo) {
               $customerlist = $this->GetCachData('getcustomer', $res['id']);
               if ($userinfo['kefu'] != 0) {
                   $res['weixin'] = @$customerlist[$userinfo['kefu'] - 1]['commission'];
               } else {
                   if (!empty($customerlist)) {
                       $this->setcustomer($res['id'], $customerlist);
                       $nub = count($customerlist);
                       $i = intval($userinfo['id']) % $nub;
                       $res['weixin'] = $customerlist[$i]['commission'];
                   }
               }
         }*/

        $res['zfb']='http://'.$host.'/public/uploads/pic/webinfo/zfb.jpg';

        if ($getmsg) {
            $msg['code'] = 0;
            unset($res['owner']);
            $msg['data'] = $res;
            $this->sendjsonmsg($msg);
        }
        return $res;
    }


    public function checklogin()
    {
        $header = getallheaders();
        // var_dump($header); exit;
        $this->load->helper('url');
        $this->load->library('session');
        $row['islogin'] = $this->session->islogin;
        $row['herder'] = $header;
        $this->addlog($row);
        if (isset($header['Sec-Fetch-Mode'])) {
            exit;
        }
        if (!$this->session->islogin) {
            $class = $this->router->class;
            if (strtolower($class) == 'welcome' || strtolower($class) == 'tools') {
                return strtolower($class);
            } else {
                if (!isset($header['Isajax'])) {
                    //redirect(base_url() . '/Welcome/register');
                    redirect(base_url() . '/seller');
                } else {
                    $arr = array();
                    $arr['code'] = 400;
                    $arr['msg'] = '未登录';
                    $this->sendjsonmsg($arr);
                }
            }
        }


        $class = $this->router->class;
        return strtolower($class);
    }


    /**
     * 使用toekn进行登录
     * @return bool|mixed
     */
    public function tokenlogin()
    {
        $class = $this->router->class;
        $header = getallheaders();
        if (isset($header['Token']) || isset($header['Accesstoken'])) {
            $MYredis = $this->MyRedis();
            if (isset($header['Token'])) {
                $value = $MYredis->get($header['Token']);
            } else {
                $value = $MYredis->get($header['Accesstoken']);
            }
            if ($value) {
                $value = unserialize($value);
                $this->session->username = $value['username'];
                $this->session->islogin = 1;
                $this->session->user_id = $value['id'];
                $this->setuserinfo($value);
            }
            return $value;
        }
        return false;
    }


    /**
     * 根据不同身份进行跳转
     * @param $group
     */
    public function groupjunp($group)
    {
        if ($group == 1 || $group == 4 || $group == 5 || $group == 6) {
            if (ISHOST) {//本地
                redirect(base_url() . '/Customer/index');
            }
            $url = base_url() . 'manage/';
            $url = str_replace("www.", "admin.", $url);
            redirect($url);
        }
        if ($group == 2) {
            redirect(base_url() . '/business/index');
        }
        if ($group == 3) {
            redirect(base_url() . '/hunter/index');
        }
    }


    /**
     * 获取配置
     */
    public function getconfig($name)
    {
        $this->load->model('Jd_config_model');
        $MYredis = $this->MyRedis();
        $key = "xinquanzhongconfig";
        $key = $key . "|" . $this->web_id;
        $value = $MYredis->hGet($key, $name);
        if (!$value) {
            $value = $this->Jd_config_model->GetByname($name);
            $value = $value['value'];
            $MYredis->hSet($key, $name, $value);
            $ttl = $MYredis->ttl($key);
            if ($ttl == -1) {
                $MYredis->expire($key, 15 * 60);
            }
        }
        if ($value) {
            $value = unserialize($value);
        }
        return $value;
    }


    public function sendjsonmsg($row = array())
    {
        if (empty($row['code'])) {
            $row['code'] = 0;
        }
        if (empty($row['msg'])) {
            $row['msg'] = "无消息";
        }
        echo json_encode($row);
        exit;
    }

    public function gettimesqlstr($filed = "p1.addtime", $str1 = 'date1', $str2 = 'date2')
    {
        $date1 = $this->input->post($str1) ? $this->input->post($str1) : null;
        $date2 = $this->input->post($str2) ? $this->input->post($str2) : null;
        $where = "";
        if ($date1) {
            $date1 = strtotime(date('Y-m-d 00:00:00', strtotime($date1)));
            $where .= " AND " . $filed . ">$date1 ";
        }
        if ($date2) {
            $date2 = strtotime(date('Y-m-d 23:59:59', strtotime($date2)));
            $where .= " AND " . $filed . "<$date2 ";
        }
        return $where;
    }

    /**
     * 获取用户信息
     */
    public function getcuserinfo($getall = 0, $user_id = 0)
    {
        $userinfo = $this->userinfo = $this->session->userinfo;
        if ($getall == 1 || empty($userinfo)) {
            if (empty($user_id)) {
                $user_id = $this->session->user_id;
            }
            $this->load->model('Jd_users_model');
            $userinfo = $this->Jd_users_model->GetUserById($user_id);
            $userinfo = $userinfo;
        }
        return $userinfo;
    }


    public function ResetUserinfo()
    {
        $userinfo = $this->getcuserinfo(1);
        $this->setuserinfo($userinfo);
    }

    /**
     * 设置用户信息
     */
    public function setuserinfo($userinfo)
    {
        $this->user_id = $userinfo['id'];
        $this->username = $userinfo['username'];
        if (empty($userinfo['team'])) {
            $userinfo['team'] = "";
        } else {
            $this->load->model('Jd_group_model');
            //$userinfo['team'] = $this->Jd_group_model->getteambyuserid($userinfo['team']);
        }
        $this->session->userinfo = $userinfo;
        $this->session->username = $userinfo['username'];
    }


    /**
     * 设置推广链接
     * @param $user_id
     */
    public function SetExtensionLink($user_id, $type = '')
    {
        $link = base_url() . "welcome/sign/";
        $key = $type . $user_id;
        //$key = base64_encode($key);
        //$key = urlencode($key);
        $link = $link . $key;
        return $link;
    }

    /**
     * 将URL格式的字符串转化为ID
     *
     * @param String $str
     * @return Array(goods_type, goods_id)
     */
    public function Url2Key($key, $type = 'reg_invite')
    {
        $newkey = base64_decode(urldecode($key));
        $res = explode($type, $newkey);
        if (!isset($res[1])) {
            $res = array();
            $res[1] = $key;
        }
        return $res;
    }


    public function getgrouplist($type = 0)
    {
        $this->load->model('Jd_group_model');
        $r = $this->Jd_group_model->getgrouplist();
        if ($type) {
            $lsit = array();
            foreach ($r as $id => $v) {
                $lsit[$v['id']] = $v['name'];
            }
            return $lsit;
        }
        return $r;
    }

    public function getteamlist($type = 0)
    {
        $this->load->model('Jd_group_model');
        $r = $this->Jd_group_model->getteamlist();

        if ($type) {
            $lsit = array();
            foreach ($r as $id => $v) {
                $lsit[$v['id']] = $v['name'];
            }
            return $lsit;
        }
        return $r;
    }

    public function getchannellist($type = 0)
    {
        $this->load->model('Jd_group_model');
        $r = $this->Jd_group_model->getchannellist();
        if ($type) {
            $lsit = array();
            foreach ($r as $id => $v) {
                $lsit[$v['id']] = $v['name'];
            }
            return $lsit;
        }
        return $r;
    }


    /**
     * 获取一些类缓存的数组 例如 getgrouplist getteamlist getchannellist
     * @param $name
     * @return mixed|string
     */
    public function GetCachData($name, $type = 0)
    {
        $MYredis = $this->MyRedis();
        $key = "Dictionariescachdata";//字典数据缓存

        $value = $MYredis->hGet($key, $name . $type);
        //$value=false;
        if (!$value) {
            $value = call_user_func(array(__CLASS__, $name), $type);
            $value = serialize($value);
            $MYredis->hSet($key, $name . $type, $value);
            $ttl = $MYredis->ttl($key);
            if ($ttl == -1) {
                $MYredis->expire($key, 15 * 60);
            }
        }
        if ($value) {
            $value = unserialize($value);
        }
        return $value;
    }


    /**
     * 增量更新用户信息
     */
    public function UpdataUserinfo($row, $user_id)
    {
        $this->load->model('jd_user_total_model');
        $sql = 'update jd_user_total set ';
        $array = array();
        $array[] = 'task_nub';
        $array[] = 'task_nub_finnish';
        $array[] = 'extension';
        $array[] = 'extension_nub';
        $array[] = 'allgold';
        $array[] = 'allmoney';

        if (isset($row['update'])) {//如果有更新日期则为 邀请统计

            $row['update'] = date('Y-m-d');
            $update = $this->jd_user_total_model->getonebyuserid($user_id, 'update');
            $date = $row['update'];
            $sql = "update jd_user_total set   `update`='$date',  extension_nub_day=1, ";
            if (isset($update[0]['update']) && !empty($update[0]['update'])) {
                if ($update[0]['update'] == $row['update']) {
                    $sql = "update jd_user_total set   `update`='$date',";
                    $array[] = 'extension_nub_day';
                }
            }
        }
        $newrow = array();
        if (!empty($row)) {
            foreach ($row as $id => $v) {
                if (in_array($id, $array)) {
                    $newrow[] = "$id=$id+$v";
                }
            }
        }
        $newrow = implode(",", $newrow);
        $sql = $sql . ' ' . $newrow;
        $sql .= " where user_id=" . $user_id;
        return $result = $this->jd_user_total_model->updata_user_total($sql, $user_id);
    }


    /**
     * 商户资金检测
     */
    public function checkmoney($allmoney, $allgold)
    {
        $this->userinfo = $this->getcuserinfo(1, $this->user_id);
        $money = $this->userinfo['money'];
        $gold = $this->userinfo['gold'];
        $money = round($money, 2);


        $allmoney = round($allmoney, 2);
        if ($allmoney > $money) {
            return false;
        }
        if ($allgold > $gold) {
            return false;
        }
        return true;
    }

    /**
     * 用户资金变动
     * @param $row 变动的资金参数
     * @param string $type 资金变动类型 主要用于log记录 1 :充值 2发布任务 3 推荐奖励 4刷单,5兑换金币,6后台调整
     */
    public function moneyupdate($row, $type = "", $log_id = "")
    {
        if (empty($row['user_id'])) {
            $msg['code'] = 2;
            $msg['msg'] = "缺少用户ID";
            $this->sendjsonmsg($msg);
        }
        $user_id = $row['user_id'];
        $row = $this->chekemoneytype($row, $type);
        $this->load->model('Jd_users_model');
        $sql = 'update jd_users set ';
        $newrow = array();
        if (!empty($row)) {
            foreach ($row as $id => $v) {
                if ($id != "money" && $id != "gold" && $id != "frozenmoney" && $id != "frozengold") {
                    continue;
                }
                if ($v < 0) {
                    $v = -$v;
                    $newrow[] = "$id=$id-$v";
                } else {
                    $newrow[] = "$id=$id+$v";
                }

            }
        }
        $newrow = implode(",", $newrow);
        $sql = $sql . ' ' . $newrow;


        $result = $this->Jd_users_model->updata_user_money($sql, $user_id);

        if ($result) {
            $row['log_id'] = $log_id;
            $row['user_id'] = $user_id;
            $resl = $this->addpaylog($row, $type);
            return $resl;
        } else {
            return false;
        }
    }


    /**
     * 资金 的冻结和解除冻结
     * @param $row
     * @return mixed
     */
    public function frozenmoney($row)
    {
        if (empty($row['user_id'])) {
            $msg['code'] = 2;
            $msg['msg'] = "缺少用户ID";
            $this->sendjsonmsg($msg);
        }
        $user_id = $row['user_id'];
        $this->load->model('Jd_users_model');
        $sql = 'update jd_users set ';
        $newrow = array();
        if (!empty($row)) {
            foreach ($row as $id => $v) {
                if ($id != "money" && $id != "gold" && $id != "frozenmoney" && $id != "frozengold") {
                    continue;
                }
                if ($v < 0) {
                    $v = -$v;
                    $newrow[] = "$id=$id-$v";
                } else {
                    $newrow[] = "$id=$id+$v";
                }

            }
        }
        $newrow = implode(",", $newrow);
        $sql = $sql . ' ' . $newrow;
        return $result = $this->Jd_users_model->updata_user_money($sql, $user_id);
    }


    /**
     * 用EXCEL导出内容
     * @param $str
     * @param $list
     * @param $filename
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Writer_Exception
     */
    public function excel_out($str, $list, $filename)
    {
        $this->load->library('PHPExcel');
        $objPHPExcel = new PHPExcel();
        $filename = $filename . date('Y-m-d H:i:s') . '.xls';
        // $filename=$filename.'.xls';


        $i = 1;

        $row = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
        foreach ($str as $id => $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($row[$id] . $i, $v);
        }


        foreach ($list as $val) {
            $i++;
            $x = 0;
            foreach ($val as $id => $v) {
                if ($id == 'price' || $id == "real_price") {
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit($row[$x] . $i, $v, PHPExcel_Cell_DataType::TYPE_NUMERIC);
                } else {
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit($row[$x] . $i, $v, PHPExcel_Cell_DataType::TYPE_STRING);
                }
                $x++;
            }
        }

        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="' . $filename . '"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }


    /**
     * 用EXCEL导出内容
     * @param $str 表头
     * @param $list 数据
     * @param $filename 表名
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Writer_Exception
     */
    public function excel_out2($str, $list, $filename = "")
    {
        $this->load->library('PHPExcel');
        $objPHPExcel = new PHPExcel();
        // $filename =$filename.date('Y-m-d H:i:s').'.xls';
        $filename = $filename . '.xls';


        $i = 1;
        $x = 0;
        $row = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");

        $objPHPExcel->getActiveSheet()->getStyle('A:Z')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

        foreach ($str as $id => $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($row[$x] . $i, $v[0]);
            if (isset($v[1])) {
                $objPHPExcel->getActiveSheet()->getColumnDimension($row[$x])->setWidth($v[1]);#设置单元格宽度
            } else {
                $objPHPExcel->getActiveSheet()->getColumnDimension($row[$x])->setWidth(10);#设置单元格宽度
            }
            $x++;
        }

        foreach ($list as $val) {
            $i++;
            $x = 0;
            foreach ($str as $id => $v) {
                $objPHPExcel->getActiveSheet()->getStyle($row[$x] . $i)->getAlignment()->setWrapText(true);
                if ($id == 'price' || $id == "real_price" || $id == "money") {
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit($row[$x] . $i, $val[$id], PHPExcel_Cell_DataType::TYPE_NUMERIC);
                } else {
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit($row[$x] . $i, $val[$id], PHPExcel_Cell_DataType::TYPE_STRING);
                }
                $x++;
            }

            /*  foreach ($val as $id => $v) {
                  if(!isset($str[$id])){
                      continue;
                  }
                  $objPHPExcel->getActiveSheet()->getStyle($row[$x].$i)->getAlignment()->setWrapText(true);
                  if ($id == 'price' || $id == "real_price") {
                      $objPHPExcel->getActiveSheet()->setCellValueExplicit($row[$x] . $i, $v, PHPExcel_Cell_DataType::TYPE_NUMERIC);
                  } else {
                      $objPHPExcel->getActiveSheet()->setCellValueExplicit($row[$x] . $i, $v, PHPExcel_Cell_DataType::TYPE_STRING);
                  }
                  $x++;
              }*/
        }
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="' . $filename . '"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }


    /**
     *
     * 读取excel
     * @param $filename
     * @return array
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    public function excel_get($filename)
    {
        $this->load->library('PHPExcel');
        $objReader = PHPExcel_IOFactory::createReader("Excel5");
        // 默认使用第一个工作簿，并获取行数
        $objExcel = $objReader->load($filename);
        $sheet = $objExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();          // 取得总行数
        $highestColumn = $sheet->getHighestColumn();    // 取得总列数
        $arr = array("A", 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'C', 'I', 'J', "K", 'L');
        $row = array();
        for ($i = 1; $i <= $highestRow; $i++) {
            if ($i == 1) {
                continue;
            }
            $value = array();
            foreach ($arr as $id => $v) {
                $value[$v] = $sheet->getCell($v . $i)->getValue();
            }
            $row[] = $value;
        }
        $objExcel->disconnectWorksheets();
        unset($objExcel);
        return $row;
    }


    /*
     * 检测资本变动类型
     */
    public function chekemoneytype($row, $type)
    {

        if (in_array($type, array(2, 4, 5))) {//如果是刷单  发布任务和 兑换金币 则钱减少
            $row['money'] = -abs($row['money']);
        }
        if (isset($row['gold'])) {
            if ($type == 2) {
                $row['gold'] = -abs($row['gold']);
            }
        }
        return $row;
    }


    /**
     * type 1 :充值 2发布任务 3 推荐奖励 4刷单,5兑换金币,6后台调整
     * 用户资金记录添加
     */
    public function addpaylog($row, $type)
    {
        if (empty($row['gold'])) {
            $row['gold'] = 0;
        }
        if (empty($row['money'])) {
            $row['money'] = 0;
        }
        if (empty($row['user_id'])) {
            return false;
        }

        $this->load->model('Jd_pay_log_model');
        $userinf = $this->getcuserinfo(1, $row['user_id']);
        $row['capital'] = $userinf['money'] - $row['money'];
        $row['capital_gold'] = $userinf['gold'] - $row['gold'];
        $row['balance'] = $userinf['money'];
        $row['balance_gold'] = $userinf['gold'];
        $row['user_type'] = $userinf['group'];
        $row['type'] = $type;
        $row['webid'] = $userinf['webid'];

        $remarks = '';

        $typelist = self::getconfig('paylog_type');


        $remarks = $typelist[$type];

        if (empty($row['remarks'])) {
            $row['remarks'] = $remarks;
        }
        $row['log_type'] = $this->project;


        return $this->Jd_pay_log_model->addpaylog($row);
    }


    /**
     * 获取佣金
     * $type 1：普通订单 2高留下评订单
     */
    public function getcommission($money, $user_id = 0, $project = 0, $type = 1)
    {
        if (!$project) {
            $project = $this->project;
        }
        $commission = $this->getcommissionconfig($project, $user_id, $type);
        $key = 0;
        foreach ($commission['money'] as $id => $v) {
            if ($money > $v) {
                $key = $id;
            }
        }
        if (isset($commission['gold'][$key])) {
            $gold = $commission['gold'][$key];
        } else {
            $gold = $commission['gold'][$key - 1];
        }
        $gold = $gold + 1;
        $gold = round($gold, 2);
        return $gold;
    }

    public function getcommissionconfig($project, $user_id, $type = 0)
    {

        $this->load->model('Jd_config_model');
        $commission = self::getconfig('commission' . $type);

        if (!$commission) {
            $commission = $this->getcommissionnew($type);
        } else {
            $moneyrow = [0];
            $goldrow = [];
            $grow = [100, 1];
            foreach ($commission as $id => $v) {
                $moneyrow[] = $id;
                $goldrow[] = $v;
            }
            $row['money'] = $moneyrow;
            $row['gold'] = $goldrow;
            $row['grow'] = $grow;
            return $row;
        }
        return $commission;
    }


    /**
     *
     * @param int $type
     */
    public function getcommissionnew($type = 1, $gethost = false)
    {
        $moneyrow = [0, 50, 150, 350, 550, 650, 1050, 2050, 5050];
        $goldrow = [2, 3, 5, 7, 9, 12, 18, 25];
        $grow = [2000, 6];
        if ($type == 2) {
            $moneyrow = [0, 50, 150, 350, 550, 650, 1050, 2050, 5050];
            $goldrow = [3, 4, 6, 9, 11, 14, 17, 20];
            $grow = [2000, 3];
        }
        if ($type == 3) {
            $moneyrow = [0, 50, 150, 350, 450, 550, 650, 750, 850];
            $goldrow = [5.6, 6.6, 7.6, 8.6, 9.6, 10.6, 11.6, 12.6];
            $grow = [100, 1];
        }
        if ($type == 4) {
            $moneyrow = [0, 50, 150, 350, 450, 550, 650, 750, 850];
            $goldrow = [3, 4, 5, 6, 7, 8, 9, 10];
            $grow = [100, 1];
        }
        $row['money'] = $moneyrow;
        $row['gold'] = $goldrow;
        $row['grow'] = $grow;


        if ($this->web_id == 1 || $gethost) {
            return $row;
        }
        return $row;

    }


    /**
     * 上传图片
     */
    public function uppic($filed = "")
    {
        if (isset($_FILES['uploadFile'])) {
            $file = $_FILES['uploadFile'];//得到传输的数据
        } else {
            $file = $_FILES['file'];//得到传输的数据
        }
        $msg['code'] = 1;

        if ($file['error'] > 0) {
            $msg['msg'] = "错误类型" . $file['error'];
            $this->sendjsonmsg($msg);
        }

        $name = $file['name'];
        $type = strtolower(substr($name, strrpos($name, '.') + 1)); //得到文件类型，并且都转化成小写
        $allow_type = array('jpg', 'jpeg', 'gif', 'png'); //定义允许上传的类型

        if (!in_array($type, $allow_type)) {
            $msg['msg'] = "不允许上传" . $type . "型的文件";
            $this->sendjsonmsg($msg);
        }
        if (!is_uploaded_file($file['tmp_name'])) {
            return;
        }
        $upload_path = UPLOADS . "/pic/" . date('Y-m-d') . "/"; //上传文件的存放路径
        if ($filed) {
            $upload_path = UPLOADS . "/pic/webinfo/"; //上传文件的存放路径
        }

        if (!is_dir($upload_path)) {
            $res = mkdir($upload_path, 0777, true);
        }
        $r = move_uploaded_file($file['tmp_name'], $upload_path . $file['name']);
        if ($r) {
            $msg['code'] = 0;
            $msg['msg'] = "上传成功";
            $msg['url'] = base_url() . "public/uploads/pic/" . date('Y-m-d') . "/" . $file['name'];
            if ($filed) {
                $msg['url'] = base_url() . "public/uploads/pic/webinfo/" . $file['name'];
            }
            $msg['path'] = $upload_path . $file['name'];
            $msg['name'] = $filed;
            $this->sendjsonmsg($msg);
        }
        $msg['msg'] = "上传失败";
        $this->sendjsonmsg($msg);
    }


    /**
     * 上传文件评论
     */
    public function uptext($filed = "")
    {
        if (isset($_FILES['uploadFile'])) {
            $file = $_FILES['uploadFile'];//得到传输的数据
        } else {
            $file = $_FILES['file'];//得到传输的数据
        }
        $msg['code'] = 1;

        if ($file['error'] > 0) {
            $msg['msg'] = "错误类型" . $file['error'];
            $this->sendjsonmsg($msg);
        }

        $name = $file['name'];
        $type = strtolower(substr($name, strrpos($name, '.') + 1)); //得到文件类型，并且都转化成小写
        $allow_type = array('txt'); //定义允许上传的类型

        if (!in_array($type, $allow_type)) {
            $msg['msg'] = "不允许上传" . $type . "型的文件";
            $this->sendjsonmsg($msg);
        }
        if (!is_uploaded_file($file['tmp_name'])) {
            return;
        }
        $upload_path = UPLOADS . "/text/" . date('Y-m-d') . "/"; //上传文件的存放路径
        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0777, true);
        }
        $upload_path .= time() . rand(1000, 999) . "/";
        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0777, true);
        }

        $r = move_uploaded_file($file['tmp_name'], $upload_path . $file['name']);
        if ($r) {
            $msg['code'] = 0;
            $msg['msg'] = "上传成功";
            $msg['path'] = $upload_path . $file['name'];
            $msg['num'] = $this->gettextnum($upload_path . $file['name']);
            $this->sendjsonmsg($msg);
        }
        $msg['msg'] = "上传失败";
        $this->sendjsonmsg($msg);
    }


    public function gettextnum($upload_path)
    {

        $num = 0;
        $text = file_get_contents($upload_path);
        $sub = '/(.*?)\s\n/is';
        $r = preg_match_all($sub, $text, $row);

        foreach ($row[1] as $id => $v) {
            $v = str_replace(" ", '', $v);
            if ($v != "") {
                $num++;
            }
        }
        return $num;
    }

    /** delDir()删除文件夹及文件夹内文件函数
     * @param string $path 文件夹路径
     * @param string $delDir 是否删除改
     * @return boolean
     */
    private function delDir($path, $del = false)
    {
        $handle = opendir($path);
        if ($handle) {
            while (false !== ($item = readdir($handle))) {
                if (($item != ".") && ($item != "..")) {
                    is_dir("$path/$item") ? $this->delDir("$path/$item", $del) : unlink("$path/$item");
                }
            }

            closedir($handle);

            if ($del) {
                return rmdir($path);
            }
        } elseif (file_exists($path)) {
            return unlink($path);
        } else {
            return false;
        }
    }


    /**
     * 上传压缩包
     */
    public function uprar($filed = "")
    {
        if (isset($_FILES['uploadFile'])) {
            $file = $_FILES['uploadFile'];//得到传输的数据
        } else {
            $file = $_FILES['file'];//得到传输的数据
        }
        $msg['code'] = 1;
        if ($file['error'] > 0) {
            $msg['msg'] = "错误类型" . $file['error'];
            $this->sendjsonmsg($msg);
        }
        if ($file['size'] > 46080000) {
            $msg['msg'] = "文件过大";
            $this->sendjsonmsg($msg);
        }
        $name = $file['name'];
        $type = strtolower(substr($name, strrpos($name, '.') + 1)); //得到文件类型，并且都转化成小写
        $allow_type = array('rar', 'zip'); //定义允许上传的类型

        if (!in_array($type, $allow_type)) {
            $msg['msg'] = "不允许上传" . $type . "型的文件";
            $this->sendjsonmsg($msg);
        }
        if (!is_uploaded_file($file['tmp_name'])) {
            return;
        }
        $upload_path = UPLOADS . "/showpic/" . date('Y-m-d') . "/" . time() . rand(1000, 9999) . "/"; //上传文件的存放路径
        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0777, true);
        } else {//如果已经存在就重新生成一个随机文件夹
            $upload_path = UPLOADS . "/showpic/" . date('Y-m-d') . "/" . time() . rand(1000, 9999) . "/";
            mkdir($upload_path, 0777, true);
        }
        mkdir($upload_path . "new/", 0777, true);
        mkdir($upload_path . "old/", 0777, true);
        move_uploaded_file($file['tmp_name'], $upload_path . "old/" . "yswj" . "." . $type);
        $file['tmp_name'] = $upload_path . "old/" . "yswj" . "." . $type;
        $upload_path = $upload_path . "new/";
        if ($type == 'zip') {
            $zip = new ZipArchive();
            $res = $zip->open($file['tmp_name']);
            if ($res === true) {
                // 加入此段↓
                $fileNum = $zip->numFiles;
                for ($i = 0; $i < $fileNum; $i++) {
                    $statInfo = $zip->statIndex($i, ZipArchive::FL_ENC_RAW);
                    $zip->renameIndex($i, iconv('GBK', 'utf-8//IGNORE', $statInfo['name']));
                }
                $zip->close();
                $zip->open($file['tmp_name']);
                $res = $zip->extractTo($upload_path);//假设解压缩到在当前路径下images文件夹的子文件夹php
                $zip->close();//关闭处理的zip文件
            } else {
                $msg['msg'] = "解压失败";
                $this->sendjsonmsg($msg);
            }
        } else {
            $this->_unzip($file['tmp_name'], $upload_path);
        }
        $temp = scandir($upload_path);
        if (@is_dir($upload_path . $temp[2] . "/")) {
            $upload_path = $upload_path . $temp[2] . "/";
            $temp = scandir($upload_path);
        }
        $num = 0;
        $allow_type = array('jpg', 'jpeg', 'gif', 'png', 'txt'); //定义允许上传的类型
        $msg['code'] = 1;
        foreach ($temp as $id => $v) {
            if ($id < 2) {
                continue;
            }
            $type = strtolower(substr($v, strrpos($v, '.') + 1)); //得到文件类型，并且都转化成小写


            if ($type == "" || $type == "0") {//无文件类型说明是
                $tempchild = scandir($upload_path . "/" . $v);
                $has = 0;
                foreach ($tempchild as $id2 => $v2) {
                    if ($id2 < 2) {
                        continue;
                    }
                    if ($has > 0) {
                        unlink($upload_path . "/" . $v . "/" . $v2);
                        continue;
                    }
                    $type2 = strtolower(substr($v2, strrpos($v2, '.') + 1)); //得到文件类型，并且都转化成小写
                    if ($type2 == "") {
                        $msg['msg'] = "不允许上传多层级目录结构文件夹";
                        $this->delDir($upload_path . "/" . $v);
                        $this->sendjsonmsg($msg);
                    } else {
                        if (!in_array($type2, $allow_type)) {

                            unlink($upload_path . "/" . $v . "/" . $v2);
                        } else {
                            $has++;
                            $num++;
                        }
                    }

                }
            } else {
                if (!in_array($type, $allow_type)) {
                    unlink($upload_path . "/" . $v);
                } else {
                    $num++;
                }
            }
        }
        $msg['code'] = 0;
        $msg['msg'] = "上传成功";
        $msg['path'] = $upload_path;
        $msg['num'] = $num;
        $this->sendjsonmsg($msg);
        $msg['msg'] = "上传失败";
        $this->sendjsonmsg($msg);
    }

    public function getpicnum($upload_path)
    {
        $temp = scandir($upload_path);
        $num = 0;
        foreach ($temp as $id => $v) {
            if ($id < 2) {
                continue;
            }
            $type = strtolower(substr($v, strrpos($v, '.') + 1)); //得到文件类型，并且都转化成小写
            if ($type == "") {//无文件类型说明是
                $tempchild = scandir($upload_path . "/" . $v);
                foreach ($tempchild as $id2 => $v2) {
                    if ($id2 < 2) {
                        continue;
                    }
                    $num++;
                }
            } else {
                $num++;
            }

        }
        return $num;
    }

    public function _unzip($fileName, $extractTO)
    {
        $this->load->library('RAR');
        $RAR = new RAR;

        return $RAR->decompression($fileName, $extractTO);

        $rar_file = rar_open($fileName) or die('could not open rar');
        $list = rar_list($rar_file) or die('could not get list');
        $i = 0;
        foreach ($list as $file) {
            $pattern = '/\".*\"/';
            preg_match($pattern, $file, $matches, PREG_OFFSET_CAPTURE);
            $pathStr = $matches[0][0];
            $pathStr = str_replace("\"", '', $pathStr);

            $entry = rar_entry_get($rar_file, $pathStr) or die('</br>entry not found');
            $entry->extract($extractTO); // extract to the current dir
        }
        rar_close($rar_file);
        return true;
    }


    public function saveshowpic($taskid)
    {
        $row = $this->input->post();
        $type_h = $row['type_h'];
        $list = array();
        if ($type_h == 2 && isset($row['showpicpath']) && $row['showpicpath']) {
            $this->load->model('Jd_pic_model');
            $upload_path = $row['showpicpath'];
            $temp = scandir($row['showpicpath']);
            foreach ($temp as $id => $v) {
                if ($id < 2) {
                    continue;
                }
                $type = strtolower(substr($v, strrpos($v, '.') + 1)); //得到文件类型，并且都转化成小写
                if ($type == "") {//无文件类型说明是
                    $tempchild = scandir($upload_path . "/" . $v);
                    foreach ($tempchild as $id2 => $v2) {
                        if ($id2 < 2) {
                            continue;
                        }
                        $newrow = array();
                        $newrow['user_id'] = $this->user_id;
                        $newrow['address'] = $upload_path . $v . "/" . $v2;
                        $newrow['url'] = str_replace(UPLOADS, "", $upload_path . $v) . "/" . $v2;
                        $newrow['taskid'] = $taskid;
                        $newrow['addtime'] = time();
                        $result = $this->Jd_pic_model->addpic($newrow);
                        if (!$result) {
                            $msg['code'] = 1;
                            $msg['msg'] = '图片上传失败';
                            $this->sendjsonmsg($msg);
                        }
                        $list[] = $result;
                    }
                } else {
                    $newrow = array();
                    $newrow['user_id'] = $this->user_id;
                    $newrow['address'] = $upload_path . $v;
                    $newrow['url'] = str_replace(UPLOADS, "", $upload_path) . $v;
                    $newrow['taskid'] = $taskid;
                    $newrow['addtime'] = time();
                    $result = $this->Jd_pic_model->addpic($newrow);
                    if (!$result) {
                        $msg['code'] = 1;
                        $msg['msg'] = '图片上传失败';
                        $this->sendjsonmsg($msg);
                    }
                    $list[] = $result;
                }
            }
        }
        return $list;
    }

    public function savetext($taskid)
    {
        $row = $this->input->post();
        $type_h = $row['type_h'];
        $list = array();

        if ($type_h == 2 && isset($row['textpath']) && $row['textpath']) {
            $upload_path = $row['textpath'];
            $this->load->model('Jd_pic_model');
            $text = file_get_contents($row['textpath']);
            $sub = '/(.*?)\s\n/is';
            $r = preg_match_all($sub, $text, $row);
            foreach ($row[1] as $id => $v) {
                $v = str_replace(" ", '', $v);
                if ($v != "") {
                    $newrow = array();
                    $newrow['user_id'] = $this->user_id;
                    $newrow['address'] = $upload_path;
                    $newrow['text'] = $v;
                    $newrow['taskid'] = $taskid;
                    $newrow['addtime'] = time();
                    $result = $this->Jd_pic_model->addtext($newrow);
                    if (!$result) {
                        $msg['code'] = 1;
                        $msg['msg'] = '评论上传失败';
                        $this->sendjsonmsg($msg);
                    }
                    $list[] = $result;
                }
            }
        }
        return $list;
    }


    public function movepic($file)
    {
        $filestr = explode(".", $file);


        $count = count($filestr);
        $type = $filestr[$count - 1];

        $newFile = UPLOADS . "/pic/" . date('Y-m-d') . "/";
        if (!is_dir($newFile)) {
            $res = mkdir($newFile, 0777, true);
        }
        $newFile2 = time() . "." . $type;
        $newFile = $newFile . $newFile2;
        $url = "/pic/" . date('Y-m-d') . "/" . $newFile2;
        $r = copy($file, $newFile); //拷贝到新目录
        if (!$r) {
            return false;
        }
        //unlink($file); //删除旧目录下的文件
        $row['path'] = $newFile;
        $row['url'] = $url;
        return $row;
    }


    public function MyRedis($type = 0)
    {
        $config = $this->config->item('redis');
        require_once(FCPATH . 'application/libraries/MYredis.php');
        return MYredis::getInstance($config, $this->web_id);
    }


    public function Resetpoolsnumber()
    {
        $this->load->model('Jd_task_jd_list_pool_model');
        $result = $this->Jd_task_jd_list_pool_model->getpoolsnumber();
        $redis = $this->MyRedis();
        foreach ($result as $id => $v) {
            $redis->set('poolnub' . $v['type'], $v['num']);
        }
        echo $redis->get('poolnub1') . "__" . $redis->get('poolnub2');
        exit;
    }


    /**
     * 发送短信
     */
    public function sendSms($phone, $code)
    {
        require_once(FCPATH . 'application/libraries/aliyun-dysms-php-sdk-lite/SignatureHelper.php');
        $params = array();
        // *** 需用户填写部分 ***
        // fixme 必填：是否启用https
        $security = false;

        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId = "LTAI4Fy8eCg9PyoQcAWX3ygj";
        $accessKeySecret = "Dt7hmtpQgFcl0QMYdGuWfsfCfmNqPS";


        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $phone;

        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = "新权重";


        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = "SMS_199195548";


        /*  $accessKeyId = "LTAI59ZOZ2HVk0fQ";
          $accessKeySecret = "ng5QqEOHZnxeVqSZSiCExQndfXffTl";
          $params["SignName"] = "猎手系统注册";
          $params["TemplateCode"] = "SMS_170838069";*/
        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = array(
            "code" => $code
        );

        // fixme 可选: 设置发送短信流水号
        $params['OutId'] = date("Ymd") . rand(10000, 99999);

        // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
        $params['SmsUpExtendCode'] = "";


        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }

        //  初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();

        // 此处可能会抛出异常，注意catch
        $content = $helper->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            )),
            $security
        );
        $content = (array)$content;

        return $content;
    }


    public function sendMSG($phone, $code)
    {

        $URL = 'http://www.lokapi.cn/smsUTF8.aspx';
        $URL = 'http://www.lokapi.cn/smsUTF8.aspx';
        $row = array();
        $row['action'] = 'sendinternation';
        $row['action'] = 'sendtemplate';


        $row['username'] = '15212414880';
        $row['password'] = MD5('15212414880');
        $row['token'] = 'b780aa51';
        $row['templateid'] = 'C51C3630';
        $row['param'] = $phone . "|" . $code . "|5";
        $t = explode(" ", microtime());
        $microsecond = round(round($t[1] . substr($t[0], 2, 3)));
        $row['timestamp'] = $microsecond;
        $sign = array();
        //ksort($row);
        $sinrow = ['action', 'username', 'password', 'token', 'timestamp'];
        foreach ($row as $id => $v) {
            if (in_array($id, $sinrow)) {
                $sign[] = $id . "=" . $v;
            }
        }
        $sign = implode("&", $sign);
        $row['sign'] = MD5($sign);
        $str = array();
        foreach ($row as $id => $v) {
            $str[] = $id . "=" . $v;
        }
        $str = implode("&", $str);

        $res = $this->curl_post($URL, $str);


        return $res;
    }

    // post请求
    function curl_post($url, $curlPost)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     *  检测当前用户的邀请人或者自己是否可以升级为VIP
     */
    public function checkvip()
    {

        $this->load->model('Jd_users_model');
        $result = $this->Jd_users_model->GetUserById($this->user_id);
        if ($result['recommender_id']) {//检测其邀请人
            $num = $this->Jd_users_model->tuijiansend($result['recommender_id']);
            if ($num) {
                $this->Jd_users_model->addvip($result['recommender_id']);
            }
        }
        if ($this->is_vip) {
            return;
        }
        $this->load->model('jd_user_total_model');
        $update = $this->jd_user_total_model->getonebyuserid($this->user_id, 'task_nub');
        if (!empty($update[0]) && $update[0]['task_nub'] >= 1500) {
            $this->Jd_users_model->addvip($this->user_id);
        }
    }


    public function checkInvitation()
    {
        if (!$this->userinfo['recommender_id']) {
            return;
        }
        $this->load->model('jd_user_total_model');
        $update = $this->jd_user_total_model->getonebyuserid($this->user_id, 'task_nub');
        if (!empty($update[0]) && $update[0]['task_nub'] == 1) {
            $newrow = array();
            $newrow['user_id'] = $this->userinfo['recommender_id'];
            $newrow['gold'] = 10;
            $this->moneyupdate($newrow, 3, $this->user_id);
        }
    }


    /**
     * 依据给的表名和数组参数 结合接收的post参数 构建SQL语句字符串
     * @param $tablename 表名
     * @param $row 需要接收的字段数组
     * @param $post 接收的post参数
     * @return string
     */
    public function getsqlstrbyrow($row = [], $tablename = 'p1')
    {
        $sql = "";
        $post = $this->input->post();

        foreach ($row as $key => $v) {
            if (isset($post[$v]) && $post[$v] != "") {
                $value = $post[$v];
                if (!is_numeric($value)) {
                    $sql .= " AND " . $tablename . "." . $v . "= '$value'";
                } else {
                    $sql .= " AND " . $tablename . "." . $v . "= $value";
                }


            }
        }
        return $sql;
    }


    /**
     * 将excel转化为数组
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    public function setexcelToArray()
    {

        if (isset($_FILES['uploadFile'])) {
            $file = $_FILES['uploadFile'];//得到传输的数据
        } else {
            $file = $_FILES['file'];//得到传输的数据
        }
        $msg['code'] = 1;
        if ($file['error'] > 0) {
            $msg['msg'] = "错误类型" . $file['error'];
            $this->sendjsonmsg($msg);
        }

        $name = $file['name'];
        $type = strtolower(substr($name, strrpos($name, '.') + 1)); //得到文件类型，并且都转化成小写
        $allow_type = array('xls'); //定义允许上传的类型
        if (!in_array($type, $allow_type)) {
            $msg['msg'] = "不允许上传" . $type . "型的文件";
            $this->sendjsonmsg($msg);
        }
        if (!is_uploaded_file($file['tmp_name'])) {
            return;
        }
        @$row = $this->excel_get($file['tmp_name']);
        if (empty($row)) {
            $msg['msg'] = "数据为空";
            $this->sendjsonmsg($msg);
        }
        return $row;
    }


    /**
     *对某个表进行基础的 增 删 改
     * @param $tablename //表名
     * @param $type //类型 add 添加 edit 修改 del 删除
     */
    public function modelController($tablename, $type, $row = array())
    {
        $pass = false;
        if (empty($row)) {
            $row = $this->input->post();
        } else {
            $pass = true;
        }

        foreach ($row as $id => $v) {
            $row[$id] = trim($v);
        }
        $moddelname = 'jd_' . $tablename . '_model';
        $this->load->model($moddelname);
        if ($type == 'add') {//添加
            $array['addtime'] = time();
            $r = $this->$moddelname->add($tablename, $row);
        }
        if ($type == 'edit') {
            if (isset($row['primary'])) {
                $primary = $row['primary'];
                $id = $row[$primary];
                unset($row['primary']);
                unset($row[$primary]);
            } else {
                if (!isset($row['id'])) {
                    $msg['code'] = 1;
                    $msg['msg'] = "缺少更新主键";
                    $this->sendjsonmsg($msg);
                }
                $primary = 'id';
                $id = $row['id'];
                unset($row['id']);
            }
            $r = $this->$moddelname->update($tablename, $primary, $id, $row, $limit = 1);
        }
        if ($type == 'del') {
            if (isset($row['primary'])) {
                $primary = $row['primary'];
                $id = $row[$primary];
                unset($row['primary']);
                unset($row[$primary]);
            } else {
                if (!isset($row['id'])) {
                    $msg['code'] = 1;
                    $msg['msg'] = "缺少删除主键";
                    $this->sendjsonmsg($msg);
                }
                $primary = 'id';
                $id = $row['id'];
                unset($row['id']);
            }
            $r = $this->$moddelname->delete($tablename, $primary, $id);
        }
        if (!$r) {
            $msg['code'] = 1;
            $msg['msg'] = "操作失败";
            $this->sendjsonmsg($msg);
        }
        if (!$pass) {
            $this->sendjsonmsg();
        }
        return $r;

    }


    /**
     * 获取列表
     * @param $tablename //表名
     */
    public function getTableList($tablename)
    {

        $leftuser = $this->input->post('leftuser') ? $this->input->post('leftuser') : false;
        $page = $this->input->post('page');
        $epage = $this->input->post('epage');
        if (empty($epage)) {
            $epage = 10;
        }
        $_POST['webid'] = $this->web_id;
        $where = "where  1=1  ";
        $where .= $this->getsqlstrbyrow(['id', 'user_id', 'webid']);
        if ($leftuser) {
            $where .= $this->getsqlstrbyrow(['username'], "p2");
        }

        $where .= $this->gettimesqlstr();
        $_select = "p1.*";
        if ($leftuser) {
            $_select .= ",p2.username";
        }
        $tablename = 'jd_' . $tablename;
        $_order = " order by p1.id desc ";
        $sql = "select SELECT from `$tablename` as p1";
        if ($leftuser) {
            $sql .= " left join  `jd_users` as p2  on   p1.user_id=p2.id ";
        }
        $sql .= ' SQL ORDER LIMIT ';
        $_data = array("sql" => $sql,
            "_sql" => $where,
            "_select" => $_select,
            "_order" => $_order,
            "limit" => "",
            "page" => $page,
            "epage" => $epage);

        $this->load->model('Jd_task_jd_list_model');
        $a = $this->Jd_task_jd_list_model->get_server_list($_data);
        $a['epage'] = $epage;
        $a['page'] = $page;
        foreach ($a['list'] as $id => $v) {
            $a['list'][$id]['addtime'] = date("Y-m-d H:i:s", $v['addtime']);
        }
        $this->sendjsonmsg($a);
    }


    public function getcustomer($webid)
    {
        $this->load->model('Jd_users_model');
        return $this->Jd_users_model->getneedset($webid);

    }


    public function setcustomer($webid, $row)
    {

        $this->load->model('Jd_users_model');


        $this->Jd_users_model->dbsetcustomer($webid, $row);

    }

}
